<?php


namespace App\Http\Controllers;

use App\Exceptions\ExceptionApi;
use App\Http\Response\UserResponse;
use App\Http\Response\VideoResponse;
use App\Models\LikeVideo;
use App\Models\User;
use App\Models\Video;
use App\Services\Logger;
use App\Services\Uri;
use Illuminate\Http\Response;
use Illuminate\Http\Request;

class UserController extends Controller
{

    /**
     * @api {GET} /api/member/getInfo 个人中心
     * @apiGroup 用户中心
     * @apiDescription 获取用户基本信息
     * @apiUse PublicCommonBlock
     * @apiSuccessExample {json} 成功相应示例
     * {"code":200,"msg":"success","data":{"id":1,"nickname":"nick harvey","avatar":"https:\/\/dy.zq.xiantou.com\/uploads\/default.png","token":"tkb.de870612aab42f91bd98841088f0b14987ecd7bc88ede0b4ba19078c00bf3cc3.1"}}
     */
    public function index(Request $request) :Response
    {
        $user = $request->user;
        $data = UserResponse::toArray($user);
        return $this->success($data);
    }

    /**
     * @api {POST} /api/Appupload 上传图片
     * @apiGroup 用户中心
     * @apiDescription 上传图片
     * @apiUse PublicCommonBlock
     * @apiSuccessExample {json} 成功相应示例
     * {}
     */
    public function uploadImage(Request $request) :Response
    {
        // 你可以使用 file 方法或使用动态属性从 Illuminate\Http\Request 实例中访问上传的文件。
        // 该 file 方法返回 Illuminate\Http\UploadedFile 类的实例，
        //该类继承了 PHP 的 SplFileInfo 类的同时也提供了各种与文件交互的方法：

        if(!$request->file('card')->isValid()){
            throw new ExceptionApi('上传文件不符合要求');
        }
        $image = $request->file('card');
        Logger::debug(var_export($image,true));
        $path = $image->store('images', 'uploads');
        if($path==false){
            throw new ExceptionApi('文件上传失败,请稍后再试');
        }
        $url = Uri::createImageUrl($path);
        return $this->success(['src'=>$path,'url'=>$url]);
    }

    /**
     * @api {POST} /api/member/editInfo 更新用户信息
     * @apiGroup 用户中心
     * @apiDescription 更新用户昵称和头像
     * @apiUse PublicCommonBlock
     * @apiSuccessExample {json} 成功相应示例
     * {}
     */
    public function update(Request $request) :Response
    {
        $user = $request->user;
        $image = $request->input('avatar');
        $nickname = $request->input('nickname');
        if($image){
            $user->image = $image;
            $user->save();
            return $this->success(null, '头像修改成功');
        }
        if($nickname){
            $user->nickname = $nickname;
            $user->save();
            return $this->success(null,'更改昵称成功');
        }

        return $this->success(null);
    }


    /**
     * @api {POST} /api/member/likeVideo 点赞短视频
     * @apiGroup 短视频
     * @apiDescription 点赞|取消点赞短视频
     * @apiUse CommonBlock
     * @apiParam {Integer} id 短视频ID
     * @apiSuccessExample {json} 成功相应示例
     * {}
     */
    public function likeVideo(Request $request) :Response {
        $userId = $request->user->id;
        $videoId = $request->input('id');
        $likeVideo = LikeVideo::query()->where(['user_id'=>$userId,'video_id'=>$videoId])->first();

        $videoModel = Video::query()->find($videoId);

        $hasLike = 0;
        if($likeVideo){
            $likeVideo->delete();
            if($videoModel){
                // 视频总点赞数-1
                $videoModel->decrement('likes_num',1);
            }
            return $this->success(['has_like'=>$hasLike],'点赞已取消');
        }

        if(!$videoModel){
            throw new ExceptionApi('视频不存在');
        }
        $likeVideo = new LikeVideo();
        $likeVideo->user_id = $userId;
        $likeVideo->video_id = $videoId;
        $likeVideo->save();
        // 视频总点赞数+1
        $videoModel->increment('likes_num', 1);

        $hasLike = 1;
        return $this->success(['has_like'=>$hasLike], '点赞成功');
    }

    /**
     * @api {GET} /api/member/getLikeVideos 获取点赞视频列表
     * @apiGroup 短视频
     * @apiDescription 喜欢的视频列表
     * @apiUse CommonBlock
     * @apiSuccessExample {json} 成功相应示例
     * {}
     */
    public function getLikeVideos(Request $request) :Response {
        /* @var User $user */
        $user = $request->user;
        $videos = $user->getLikeVideos();
        $total = $user->getLikeVideosTotal();
        $items = VideoResponse::getItemsList($videos, $user->getLikeVideoIds());
        return $this->success(['total'=>$total, 'items'=>$items]);
    }


    /**
     * @api {GET} /api/member/getVideosByIds 通过ID获取视频列表
     * @apiGroup 短视频
     * @apiDescription 通过ID获取视频列表
     * @apiUse CommonBlock
     * @apiParam {String} ids 视频ID列表。 例： [1,2,3,8,10]
     * @apiSuccessExample {json} 成功相应示例
     * {}
     */
    public function getVideosByIds(Request $request) :Response {
        $ids = $request->input('ids');
        $ids = json_decode($ids,true);
        if(!$ids){
            throw new ExceptionApi('ids参数解析错误');
        }
        $query = Video::query()->whereIn('id', $ids);
        $total = $query->count();
        $items = $query->get();
        $user = $request->user;
        $likeVideoIds = $user->getLikeVideoIds();
        $items = VideoResponse::getItemsList($items, $likeVideoIds);
        return $this->success(['total'=>$total, 'items'=>$items]);
    }

}
